/**
 * com.sunrise.commons.utils.Md5.java
 */
package com.mbmed.doctor.commons.utils;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @file Md5.java
 * @author 贾海勇
 * @version 0.1
 * @todo MD5加密功能 Copyright(C), 2013-2014 Shenzhen Coordinates Software
 *       Development Co., Ltd History 1. Date: 2013-4-18 Author: 贾海勇
 *       Modification: this file was created 2. ...
 */
public class Md5 {
	private String ALGO;

	private byte[] keyValue;

	/**
	 * 用来进行加密的操作
	 * 
	 * @param Data
	 * @return
	 * @throws Exception
	 */
	public String encrypt(String Data) throws Exception {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] encVal = c.doFinal(Data.getBytes());
		String encryptedValue = new BASE64Encoder().encode(encVal);
		return encryptedValue;
	}

	/**
	 * 用来进行解密的操作
	 * 
	 * @param encryptedData
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String encryptedDa) throws Exception {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.DECRYPT_MODE, key);
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedDa);
		byte[] decValue = c.doFinal(decordedValue);
		String decryptedValue = new String(decValue);
		return decryptedValue;
	}

	/**
	 * 根据密钥和算法生成Key
	 * 
	 * @return
	 * @throws Exception
	 */
	private Key generateKey() throws Exception {
		Key key = new SecretKeySpec(keyValue, ALGO);
		return key;
	}

	public String getALGO() {
		return ALGO;
	}

	public void setALGO(String aLGO) {
		ALGO = aLGO;
	}

	public byte[] getKeyValue() {
		return keyValue;
	}

	public void setKeyValue(byte[] keyValue) {
		this.keyValue = keyValue;
	}

	// 测试
	public static void main(String[] args) throws Exception {
		Md5 md5 = new Md5();
		md5.setALGO("AES");
		md5.setKeyValue("4E7FF1C1F04F4B36".getBytes());
		String pwd = "admin";
		String enPwd = md5.encrypt(pwd);
		System.out.println("加密后密码---------》" + enPwd);
		String dePwd = md5.decrypt("7ixpVg7WxLhUIcuUS5gPEg==");
		System.out.println("解密后的密码:------------>" + dePwd);
	}

}
